package com.ruoyi.stateMachineDemo.service.impl;

import com.ruoyi.stateMachineDemo.Events;
import com.ruoyi.stateMachineDemo.States;
import com.ruoyi.stateMachineDemo.bean.GoodOrder;
import com.ruoyi.stateMachineDemo.service.GoodOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.statemachine.StateMachine;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class GoodOrderServiceImpl implements GoodOrderService {

    @Autowired
    private StateMachine<States, Events> stateMachine;

    /**
     * 创建订单
     * @param order
     */
    @Override
    public void createOrder(GoodOrder order) {
        stateMachine.start();
        System.out.println("当前订单状态："+stateMachine.getState().getId());
    }

    /**
     * 支付订单
     * @param order
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void payOrder(GoodOrder order) {
        /**
         * 当为条件判断，如果可以正常执行，则再处理对应的业务逻辑，否则不做数据库处理
         */
        if(order.getStatus()!=States.UNPAID.getValue()){
            throw new RuntimeException("当前状态不支持付款");
        }else{
            stateMachine.start();
        }
        boolean b = stateMachine.sendEvent(Events.PAY);
        if (!b) {
            throw new RuntimeException("支付异常");
        }
        /**
         * 执行数据库操作
         */
        System.out.println("执行数据库操作:修改当前状态为："+stateMachine.getState().getId());
    }

    @Override
    public void receive(GoodOrder order) {
        if(order.getStatus()!=States.WAITING_FOR_RECEIVE.getValue()){
            throw new RuntimeException("当前状态不支持收货");
        }else{
            stateMachine.start();
            stateMachine.sendEvent(Events.PAY);
        }
        boolean b = stateMachine.sendEvent(Events.RECEIVE);
        if (!b) {
            throw new RuntimeException("收货异常");
        }
        /**
         * 执行数据库操作
         */
        System.out.println("执行数据库操作:修改当前状态为："+stateMachine.getState().getId());
    }
}
